/**
 * Hawk Library Riak File Engine Module
 * ------------------------------
 * Riak File Engine function module
 */

"use strict";
var fs    = require('fs');
var radon = require('radon');
var http  = require('http');

exports.putFile = function(bucket_url, key, path, type){
	if (!type){
		type = exports.pathToType(path);
	}

	try {
		var stream = fs.createReadStream(path);
	}catch (e){
		radon.throw(10000100);
	}
	try {
		var res = http.post(
			bucket_url + key,
			stream,
			{'Content-Type': type}
		);
		if (res.status == 204){
			return true;
		}else {
			radon.throw(10000102, [res.readAll().toString()]);
		}
	}catch (e){
		radon.throw(10000101);
	}
}

var TYPES = {
	'png': 'image/png',
	'gif': 'image/gif',
	'jpg': 'image/jpeg',
	'jpeg': 'image/jpeg',
	'json': 'application/json',
	'js': 'application/x-javascript; charset=utf-8',
	'css': 'text/css',
	'html': 'text/html; charset=utf-8',
	'htm': 'text/html; charset=utf-8',
	'ico': 'image/x-icon'
};
exports.pathToType = function(path){
	var ext = path.split('.');
	ext = ext.length > 1 ? ext.pop().toLowerCase() : '';
	return (TYPES[ext] || 'application/octet-stream');
}
exports.formatKey = function(key){
	return key.replace(/\//g, '_');
}